<?php
/**
 * Anchor view helper
 *
 * Creates formats a new anchor tag (<a>)
 *
 * @category    IPB_CMS
 * @package     App_View
 * @subpackage  Helper
 * @copyright   Copyright (c) 2009 IPB CMS <http://ipb-cms.googlecode.com/>
 * @license     http://www.gnu.org/licenses/gpl-3.0.html GNU General Public License
 * @author      Henrique Moody <henriquemoody@gmail.com>
 */
class App_View_Helper_Anchor extends Zend_View_Helper_Abstract
{

    /**
     * Creates formats a new anchor tag (<a>)
     *
     * @param string $text
     * @param array $params
     * @param array $attributes
     * @return string Anchor tag
     */
    public function anchor($text, array $params, array $attributes = array())
    {
        if (!isset($params['action'])) {
            throw new Zend_View_Exception('You must provide the action.');
        }
        if (!isset($params['route'])) {
            $params['route'] = 'default';
        }

        $front         = Zend_Controller_Front::getInstance();
        $currentParams = $front->getRequest()->getParams();

        if (!isset($params['controller'])) {
            $params['controller'] = $currentParams['controller'];
        }
        if (!isset($params['module'])) {
            $params['module']     = $currentParams['module'];
        }

        $attributes['href'] = $front->getRouter()->assemble(
            array(
                'action'     => $params['action'],
                'controller' => $params['controller'],
                'module'     => $params['module']
            ),
            $params['route']
        );

        unset($params['action'], $params['controller'], $params['module'], $params['route']);

        $i = 0;
        foreach($params as $key => $value) {
            $s = $i++ == 0 ? '?' :'&amp;';
            $attributes['href'] .= $s . $key . '=' . $value;
        }

        $_text       = $this->view->translate($text);
        $_attributes = '';

        if (!isset($attributes['title'])) {
            $attributes['title'] = addslashes($_text);
        }
        foreach($attributes as $key => $value) {
            $_attributes .= " {$key}=\"{$value}\"";
        }

        $html = sprintf('<a%s>%s</a>', $_attributes, $_text);
        return $html;
    }

}
